<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>问卷设计</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="../../component/layui/css/layui.css" />
    <link rel="stylesheet" href="../../component/pear/css/pear.css" />
    <script src="../../component/layui/layui.js"></script>
    <script src="../../component/pear/pear.js"></script>
    <script src="../../component/pear/module/Sortable.min.js"></script>
    <style>
        .selected {
            border-style: dotted;
            border-width: 2px;
            border-color: rgb(175, 220, 220);
            padding: 0px;
        }
        label.required:before {   /* 给红色的必填项打红色星号（文字后）如果打前面用before*/
            content: '* ';
            color: red;
        }
    </style>
</head>

<body class="pear-container" style="overflow: scroll;background-color: gainsboro;">
    <div class="layui-row layui-col-space20" style="height: 800px;">
        <div id="left-tabs" class="layui-col-xs6 layui-col-md3" style="height: 840px;overflow: scroll;">
            <div class="layui-card" style="height: 820px;">
                <div class="layui-card-body">
                    <div class="layui-tab layui-tab-brief">
                        <ul class="layui-tab-title">
                            <li class="layui-this">基础组件</li>
                            <li>题库</li>
                        </ul>
                        <div class="layui-tab-content">
                            <div class="layui-tab-item layui-show">
                                <div class="left-tab-element">
                                    <ul class="layui-menu" id="left-tab1">
                                        <!-- 动态生成 -->
                                    </ul>
                                </div>
                            </div>
                            <div class="layui-tab-item">
                                <div class="left-tab-element">
                                    <ul class="layui-menu" id="left-tab2">
                                        <!-- 动态生成 -->
                                    </ul>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div id="mid-content" class="layui-col-xs12 layui-col-md6" style="height: 820px;">
            <div class="layui-card" style="height: 820px;">
                <div class="layui-card-body">
                    <form class="layui-form" action="" style="height: 800px;">
                        <div id="mid-scroll" class="layui-row" style="height: 90%; overflow: scroll;">
                            <div class="layui-form-item">
                                <button type="button" class="layui-btn layui-btn-sm batch-del" style="float: left;">批量删除</button>
                                <button type="button" class="layui-btn layui-btn-sm preview" style="float: right;">预览</button>
                                <button type="button" class="layui-btn layui-btn-sm logic" style="float: right;">逻辑</button>
                                <input id="title" type="text" name="title" lay-verify="required" placeholder="请输入问卷标题" class="layui-input"
                                    style="width: 400px;height: 40px;border: none;margin: 10px auto;padding: 0 0;text-align: center;">
                            </div>
                            <hr>
                            <div id="mid-form-item" style="height: 800px;">
                                <!-- 问卷内容 -->
                            </div>
                        </div>
                        <div class="layui-row">
                            <hr>
                            <div style="z-index: 9999;height: 10%; width: 100%;text-align: center;">
                                <button type="button" class="layui-btn" style="width: 100px;margin: 0px 50px;"
                                    lay-submit lay-filter="save">保存</button>
                                <button type="button" class="layui-btn close"
                                    style="width: 100px;margin: 0px 50px;">取消</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
        <div id="right-tabs" class="layui-col-xs6 layui-col-md3" style="height: 820px;">
            <div class="layui-card" style="height: 820px;">
                <div class="layui-card-body">
                    <div class="layui-tab layui-tab-brief">
                        <ul class="layui-tab-title">
                            <li class="layui-this">大纲</li>
                            <li>设置</li>
                        </ul>
                        <div class="layui-tab-content">
                            <div class="layui-tab-item layui-show">
                                <!-- 大纲 -->
                                <ul id="overview">
                                </ul>
                            </div>
                            <div class="layui-tab-item">
                                <!-- 设置 -->
                                <form id="prop" class="layui-form layui-form-pane" action=""
                                    style="width: 100%;float: left;">
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script type="text/html" id="toolbarBatchDel">
        <div class="layui-btn-container">
            <button class="layui-btn layui-btn-sm" lay-event="batchDel">批量删除</button>
        </div>
    </script>
    <script>
        layui.config({ base: '/component/pear/module/' }).use(['ques', 'form', 'table', 'rate'], function () {
            $ = layui.jquery,
                ques = layui.ques,
                sortable = layui.sortable,
                form = layui.form,
                table = layui.table,
                rate = layui.rate;

            ques.render({
                elem: '#left-tab1',
                zln: '#layui-form-item'
            });

            var sortable1, sortable2;
            //中间问卷
            sortable1 = new Sortable(document.getElementById('mid-form-item'), {
                animation: 150,
                ghostClass: 'blue-background-class',
                group: 'shared',
                onUpdate: function (evt) {
                    sortable2.sort(sortable1.toArray());
                    ques.reIndex(evt.item.dataset.id, 'sort', evt.newIndex, evt.oldIndex);
                },
                onAdd: function (evt) {
                    var _flag = evt.clone.childNodes[0].classList[1];
                    var _type = evt.clone.childNodes[0].classList[2];
                    var _obj = evt.item;
                    var _index = evt.newIndex + 1;
                    ques.insertItem(_index,_flag,_type,_obj);
                },
                scroll: true,
                handle: '.handle'
            });
            //右侧大纲
            var sortable2 = new Sortable(document.getElementById('overview'), {
                animation: 150,
                ghostClass: 'blue-background-class',
                onUpdate: function (evt) {
                    sortable1.sort(sortable2.toArray());
                    ques.reIndex(evt.item.dataset.id, 'sort', evt.newIndex, evt.oldIndex);
                },
                scroll: true
            });
            //左侧菜单
            Array.from(document.getElementsByClassName('menu')).forEach(function(item, index) {
                var sortable = new Sortable(item, {
                    animation: 150,
                    ghostClass: 'blue-background-class',
                    group: {
                        name: 'shared',
                        pull: 'clone',
                        put: false // 不允许拖拽进这个列表
                    },
                    sort: false,
                })
            });
            
            //问卷保存
            form.on('submit(save)', function (data) {
                layer.msg("保存成功!");
                console.log(ques.dataList);
            });
            //必填开关
            form.on('switch(reqSwitch)', function(data){
                ques.setRequired(data.elem.form[1].defaultValue, this.checked);
            });
            //选择校验类型
            form.on('select(verify)', function(data) {
                ques.setVerify(data.elem.form[1].defaultValue, data.value);
            });
            //问卷取消
            $('.close').on('click', function () {
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
            });
            //批量删除
            $('.batch-del').on('click', function() {
                var _html = `<div class="layui-card">
                                <div class="layui-card-body">
                                    <table id="batch-del" lay-filter="batch-del"></table>
                                </div>
                            </div>`;
                var _arr = [];
                for (let i = 0; i < ques.dataList.length; i++) {
                    _arr.push({"index": ques.dataList[i].index,
					            "id":ques.dataList[i].id,
							    "title":ques.dataList[i].title
                            });
			    }
                layer.open({
                    title: '批量删除',
                    type: 1,
                    area: ['50%', '90%'], // 宽高
                    content: _html,
                    success: function(){
                        table.render({
                            id: "batch_del",
                            elem: "#batch-del",
                            toolbar: "#toolbarBatchDel",
                            cols: [[
                                { type: 'checkbox', fixed: 'left' },
                                { field: 'index', width: 20, title: '题号'},
                                { field: 'id', width: 120, title: 'id'},
                                { field: 'title', title:'题目'}
                            ]],
                            data: _arr
                        });
                        table.on('toolbar(batch-del)', function(obj) {
                            if(obj.event === 'batchDel') {
                                var list = [];
                                table.checkStatus(obj.config.id).data.forEach(element => {
                                    list.push(element.id);
                                });
                                if(list.length == 0) {
                                    layer.msg("未选中任何记录");
                                    return;
                                }
                                ques.batchDel(list);
                                var data = table.cache['batch_del'];
                                var _arr = [];
                                for (let i = 0; i < ques.dataList.length; i++) {
                                    _arr.push({"index": ques.dataList[i].index,
                                                "id":ques.dataList[i].id,
                                                "title":ques.dataList[i].title
                                            });
                                }
                                data.splice(0, data.length, ..._arr);
                                table.renderData("batch_del");
                            }
                        });
                    }
                });
            });
            //预览
            $('.preview').on('click', function() {
                var _html = ques.getPreview();
                layer.open({
                    title: '预览',
                    type: 1,
                    area: ['50%', '90%'], // 宽高
                    content: _html,
                    success: function(){
                        // 对弹层中的表单进行初始化渲染
                        ques.renderOtherItem();
                        form.render();
                        form.on('radio(other-opt)', function (data) {
                                data.elem.parentNode.parentNode.parentNode.querySelectorAll(`input[data-id="${data.elem.name}"]`).forEach(function(item, index) {
                                    item.style.display = "none";
                                    item.setAttribute("lay-verify","");
                                });
                                data.elem.parentNode.lastElementChild.style.display = "block";
                                data.elem.parentNode.lastElementChild.setAttribute("lay-verify","required");

                                var _id = data.elem.name;
                                ques.executeLogic(_id, data.value);
                            }
                        );
                        form.on('radio(common-opt)', function (data) {
                            console.log(data);
                                data.elem.parentNode.parentNode.parentNode.querySelectorAll(`input[data-id="${data.elem.name}"]`).forEach(function(item, index) {
                                    item.style.display = "none";
                                    item.setAttribute("lay-verify","");
                                });
                                var _id = data.elem.name;
                                console.log(_id);
                                ques.executeLogic(_id, data.value);

                                // data.elem.parentNode.parentNode.parentNode.parentNode.parentNode.querySelectorAll("div.ques").forEach(function(item, index) {
                                //     item.style.display = "block";
                                // });
                            }
                        );
                        // form.on('radio(other-opt-next)', function (data) {
                        //         console.log("Test");
                        //         var _index = Array.prototype.indexOf.call(data.elem.parentNode.parentNode.parentNode.children, data.elem.parentNode.parentNode);
                        //         data.elem.parentNode.parentNode.parentNode.querySelectorAll(`input[data-id="${data.elem.name}"]`).forEach(function(item, index) {
                        //             item.style.display = "none";
                        //             item.setAttribute("lay-verify","");
                        //         });
                        //         data.elem.parentNode.lastElementChild.style.display = "block";
                        //         data.elem.parentNode.lastElementChild.setAttribute("lay-verify","required");

                        //         ques.hideItems(data.elem.name, _index);
                        //     }
                        // );
                        form.on('checkbox(other-opt)', function (data) {
                                console.log(data);
                                if(!data.elem.checked) {
                                    data.elem.parentNode.lastElementChild.style.display = "none";
                                    data.elem.parentNode.lastElementChild.setAttribute("lay-verify","");
                                }
                                else {
                                    data.elem.parentNode.lastElementChild.style.display = "block";
                                    data.elem.parentNode.lastElementChild.setAttribute("lay-verify","required");
                                }
                                var _id = data.elem.name;
                                ques.executeLogic(_id, data.value);
                            }
                        );
                        form.on('checkbox(prev-trig)', function (data) {
                            var _id = data.elem.name;
                            var _arr = [];
                            $(`input:checkbox[name='${_id}']:checked`).each(function(index, item) {
                                _arr.push($(this).val());
                            });
                            ques.executeLogic(_id, _arr);
                        });
                        form.on('select(prev-trig)', function (data) {
                            var _id = data.elem.name;
                            ques.executeLogic(_id, data.value);
                        });
                        $('.prev-input').change(function(e) {
                            console.log(e);
                        });

                        form.on('submit(pre-submit)', function (data) {
                            for (let i = 0; i < ques.dataList.length; i++) {
                                if(ques.dataList[i].type === 'checkbox') { //处理多选题
                                    var checkboxValue = "";
                                    $(`input:checkbox[name='${ques.dataList[i].id}']:checked`).each(function(index, item) {
                                        if(index == 0){
                                            checkboxValue += $(this).val();
                                        }
                                        else {
                                            checkboxValue += ',' + $(this).val();
                                        }
                                    })
                                    data.field[ques.dataList[i].id] = checkboxValue;
                                }
                            }
                            console.log(data);

                            layer.msg("提交成功!(此为预览展示)");
                        });
                        form.verify({
                            otherReq: function(value,item){
                                var verifyName = $(item).attr('name')
                                var verifyType = $(item).attr('type')
                                var formElem = $(item).parents('.layui-form')//获取当前所在的form元素，如果存在的话
                                console.log(formElem);

                                var verifyElem = formElem.find("input[name='"+verifyName+"']")//获取需要校验的元素
                                console.log(verifyElem);
                                var quesElem = formElem.find(`div.ques[data-id="${verifyName}"]`)[0];

                                if(verifyType == 'radio' || verifyType == 'checkbox') {
                                    var isTrue = verifyElem.is(':checked')//是否命中校验
                                    var focusElem = verifyElem.next().find('i.layui-icon');//焦点元素
                                    if(!isTrue && quesElem.style.display != 'none'){
                                        focusElem.css(verifyType=='radio'?{"color":"#FF5722"}:{"border-color":"#FF5722"});
                                        focusElem.first().attr("tabIndex","1").css("outline","0").blur(function() {
                                            focusElem.css(verifyType=='radio'?{"color":""}:{"border-color":""});
                                        }).focus();
                                        return '必填项不能为空';
                                    }
                                }
                                else {
                                    var focusElem = verifyElem.next().find('i.layui-icon');//焦点元素

                                    if(!value && quesElem.style.display != 'none'){
                                        focusElem.css(verifyType=='radio'?{"color":"#FF5722"}:{"border-color":"#FF5722"});
                                        focusElem.first().attr("tabIndex","1").css("outline","0").blur(function() {
                                            focusElem.css(verifyType=='radio'?{"color":""}:{"border-color":""});
                                        }).focus();
                                        return '必填项不能为空';
                                    }
                                }
                            }
                        });
                    }
                });
            });
            //逻辑
            $('.logic').on('click', function() {
                ques.renderLogicView();
            });
            //左侧题库-查看全部
            $('.getall').on('click', function(e) {
                layer.open({
                    title: '全部题目',
                    type: 2,
                    area: ['80%', '80%'],
                    content: '/view/ques/addQues.html'
                });
            });

        });
    </script>
</body>